package com.nd.rj.common.login.task;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.common.android.utils.task.progressTask.ProgressTask;
import com.nd.rj.common.R;
import com.nd.rj.common.login.NdLogin99Assistant;
import com.nd.rj.common.login.NdMiscCallbackListener;
import com.nd.rj.common.util.ComfunHelp;

/**
 * 请求短信登录发送短信验证码线程
 * 
 * <br>Created 2014-9-4 下午3:29:37
 * @version  V1.6
 * @author   linsj		
 *
 * @see 	 
 * 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 *
 */
public class LoginSendMsgCodeTask extends ProgressTask{
    /** 等待对话框 */
    private Dialog mWaitDlg;
    
    /**用户是否点击取消*/
    private boolean mbCanceled = false;
    
    /**安全中心登录助手类*/
    private NdLogin99Assistant mLogin99Assistant;
    
    /**待发送验证码的手机号码*/
    private String mstrMobile;
    
    /**图形验证码*/
    private String mstrCheckCode;
    
    /**每秒的毫秒数*/
    private final int MILLI_SECOND_PER_SECOND = 1000;
    
    /**
     * 获得等待框
     * 
     * <br>Created 2014-10-30 下午1:51:53
     * @author       linsj
     */
    private void getDialogIteration(){
        if(null != mWaitDlg){
            progressDialogIteration = new IProgressDialogIteration() {
                @Override
                public void onShow() {
                    mWaitDlg.setCanceledOnTouchOutside(false);
                    mWaitDlg.setOnKeyListener(new OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            // 屏蔽Search键(因为按搜索按键会被关闭)
                            switch (event.getKeyCode()) {
                            case KeyEvent.KEYCODE_SEARCH:
                                return true;
                            case KeyEvent.KEYCODE_BACK:
                                mbCanceled = true;
                                mWaitDlg.dismiss();
                                return true;
                            default:
                                return false;
                            }
                        }
                    });

                    mWaitDlg.show();
                }

                @Override
                public void onDismiss() {
                    mWaitDlg.dismiss();
                }
            };
        }
    }
    
    /**
     * 构造方法
     * Creates a new instance of LoginSendMsgCodeTask.
     * <br>Created 2014-9-4 下午4:28:31
     * @param context           上下文
     * @param loginAssistant    登录助手
     * @param strMobile         手机号码
     * @param strCheckCode      验证码
     * @param resId             资源ID
     */
    public LoginSendMsgCodeTask(Context context, NdLogin99Assistant loginAssistant,
            String strMobile, String strCheckCode, Dialog waitDlg) {
        super(context, R.string.nd_send_code_registing);
        mLogin99Assistant = loginAssistant;
        mstrMobile = strMobile;
        mstrCheckCode = strCheckCode;
        
        getDialogIteration();
    }

    @Override
    protected void doSuccess() {
        if(mbCanceled){
            return;
        }
        
        //成功发送验证码
        NdMiscCallbackListener.onSendMsgCodeFinish(true, 0, "");
    }

    @Override
    protected void onCancelled() {
        mbCanceled = true;
        super.onCancelled();
    }

    @Override
    protected Integer doInBackground(Void... params) {
        if(null == mLogin99Assistant){
            return R.string.login_unknow_error;
        }
        
        int iRet = 0;
        if(mbCanceled){
            return iRet;
        }
        
        //认证失败或者票据过期或者票据不存在,使用正常登录流程
        boolean isWaiting = mLogin99Assistant.isInitializing();
        while (mLogin99Assistant.isInitializing()){
            //等待初始化完成
            try {
                isWaiting=true;
                Thread.sleep(MILLI_SECOND_PER_SECOND);
                Log.d("debug", "mLogin99Assistant.isInitializing");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        if (isWaiting){
            if (!mLogin99Assistant.isInitSuccessful()){
                //刚刚初始化完成且初始化失败
                return mLogin99Assistant.getErrorCode();
            }
        }
        
        if (!mLogin99Assistant.isInitSuccessful()){
            //初始化异常，重新从初始化开始或者用户切换登录
            return doFromInit();
        }
        
        if(mbCanceled){
            return iRet;
        }
        
        //上一次初始化正常
        iRet = mLogin99Assistant.doSendMsgCode(mstrMobile, mstrCheckCode);
        
        if(mbCanceled){
            return iRet;
        }
        
        //在登录的时候，有可能用户修改了时间导致时间戳不正确
        if (mLogin99Assistant.isNeedInit()){
            //初始化异常，重新从初始化开始或者用户切换登录
            return doFromInit();
        }

        return iRet;
    }
    
    /**
     * 还没初始化的话，就从初始化开始做
     * 
     * <br>Created 2014-9-4 下午7:39:48
     * @return      操作结果状态码
     * @author       linsj
     */
    private int doFromInit(){
        int code=mLogin99Assistant.doInit();
        if (code!=0){
            return code;
        }

        return mLogin99Assistant.doSendMsgCode(mstrMobile, mstrCheckCode);
    }
    
    @Override
    protected void doFail(int result) {
        if (mbCanceled) {
            return;
        }

        String strErrMsg = "";
        if (!ComfunHelp.isNetworkAvailable(mContext)) {
            strErrMsg = mContext.getResources().getString(R.string.nd_network);
        }else if (null == mLogin99Assistant) {
            strErrMsg = mContext.getResources().getString(R.string.login_unknow_error);
        } else {
            strErrMsg = mLogin99Assistant.getErrmsg();
            if (TextUtils.isEmpty(strErrMsg)) {
                try {
                    strErrMsg = mContext.getResources().getString(result);
                } catch (Exception e) {
                    strErrMsg = mContext.getResources().getString(R.string.login_unknow_error);
                }
            }
        }
        
        NdMiscCallbackListener.onSendMsgCodeFinish(false, result, strErrMsg);
    }
}